<?php
require($_SERVER['DOCUMENT_ROOT'] . '/setting.php');
function tokengetone()
{
    global $redis_pz;
    if (!extension_loaded('redis')) {
        die('The Redis extension is not enabled');
    }
    $redis = new Redis();
    try {
        $redis->connect($redis_pz['host'], $redis_pz['port']);
    } catch (\Throwable $e) {
        die("Unable to connect to the Redis server, please check that the server address and port are correct:" . $e->getMessage());
    }
    try{
        if (!$redis->auth($redis_pz['password'])) {
            die("The Redis connection password is incorrect, please check whether the password is correct");
        }
    }catch(\Throwable $e){
        die('The Redis connection password is incorrect, please check whether the password is correct');
    }

    asyncCleanupExpiredTokens($redis);

    $ttl = 3600 * 8;
    do {
        $token = bin2hex(random_bytes(16));
        $timestamp = time() + $ttl;
        $data = [
            'token' => $token,
            'timestamp' => $timestamp
        ];
    } while ($redis->exists($token));

    try {
        $redis->setex($token, $ttl, json_encode($data));
    } catch (Exception $e) {
        die("Error storing data to Redis:" . $e->getMessage());
    }

    return $token;
}

function asyncCleanupExpiredTokens($redis)
{
    $cleanupScript = <<<'EOD'
<?php
require($_SERVER['DOCUMENT_ROOT'].'/setting.php');
$redis = new Redis();
$redis->connect($redis_pz['host'], $redis_pz['port']);
$redis->auth($redis_pz['password']);
$iterator = null;
do {
    $keys = $redis->scan($iterator, '*');
    foreach ($keys as $key) {
        if ($redis->ttl($key) < 0) { 
            $redis->delete($key); 
        }
    }
} while ($iterator !== 0); 
EOD;
    $tmpFile = tempnam(sys_get_temp_dir(), 'redis_cleanup');
    file_put_contents($tmpFile, $cleanupScript);
    $descriptorspec = [];
    try{
    $process = proc_open("php $tmpFile", $descriptorspec, $pipes);
} catch (\Throwable $e) {
    die("process_open failed");
}
    if (!is_resource($process)) {
        error_log('Failed to start async cleanup process.');
    }
    unlink($tmpFile);
}
function checknowtokentime($token)
{
    global $redis_pz;
    $redis = new Redis();
    $redis->connect($redis_pz['host'], $redis_pz['port']);
    $redis->auth($redis_pz['password']);
    $data = $redis->get($token);
    if ($data) {
        $data = json_decode($data, true);
        if ($data['timestamp'] > time()) {
            return true;
        }
    }
    return false;
}
function nowgettoken()
{
    $onetoken = tokengetone();
    return $onetoken;
}
